package com.ht.baselibs.retrofit.converter.fastjson;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONReader;
import com.ht.baselibs.bean.BaseGetBean;
import com.ht.baselibs.utils.LogUtils;
import com.ht.baselibs.utils.UIUtils;

import java.io.IOException;
import java.io.StringReader;
import java.lang.reflect.Type;

import okhttp3.ResponseBody;
import retrofit2.Converter;

/**
 * Created by WayneSuper on 25/01/2016.
 */
public class FastJsonResponseBodyConverter<T> implements Converter<ResponseBody, T> {

    private Type type;

    public FastJsonResponseBodyConverter(Type type) {
        this.type = type;
    }

    @Override
    public T convert(ResponseBody responseBody) throws IOException {
        try {
            String responseStr = responseBody.string();
            String result = responseStr.substring(0, responseStr.length());
            LogUtils.error(result);

            BaseGetBean baseGetBean = JSON.parseObject(result, BaseGetBean.class);

            if (baseGetBean.resultCode != 1000) {
                // TODO: 2017/6/15 解决选择银行问题
                if (baseGetBean.resultMessage.equals("方法调用失败")) {
                    UIUtils.showToast("输入错误,请重新输入");
                } else {
                    UIUtils.showToast(baseGetBean.resultMessage);
                }

                if (baseGetBean.resultCode == 2026) {

                }

                return null;
            }
            // TODO: 2017/6/15 此段逻辑为了处理服务器不返回数据的情况
            JSONReader reader;
            if (baseGetBean != null && baseGetBean.encryptDataResult != null) {
                reader = new JSONReader(new StringReader(baseGetBean.encryptDataResult));
            } else {
                reader = new JSONReader(new StringReader("12345"));
            }
            return reader.readObject(type);
        } finally {
            responseBody.close();
        }
    }

    public interface DecodeService {
        String decode(String data);
    }

}